package com.bvbot.json;

import static com.bvbot.core.Logger.log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.codehaus.jackson.map.ObjectMapper;

public class JsonTool {

	private final ObjectMapper mapper = new ObjectMapper();
	private static JsonTool singleton = new JsonTool();

	public static JsonTool get() {
		return singleton;
	}

	public byte[] toJson(Object object, boolean toBeZipped) {
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		try {
			if (!toBeZipped) {
				mapper.writeValue(result, object);
			} else {
				ZipOutputStream zaos = new ZipOutputStream(result);
				zaos.putNextEntry(new ZipEntry("json_content"));
				mapper.writeValue(result, object);
				zaos.closeEntry();
				zaos.close();
			}
		} catch (IOException e) {
			log("Exception  : " + e.getMessage(), e);
		}
		return result.toByteArray();
	}

	public <T> T fromJson(Class<T> theClass, byte[] bytes, boolean wasZipped) {
		T result = null;
		try {
			if (!wasZipped) {
				result = mapper.readValue(bytes, theClass);
			} else {
				ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
				ZipInputStream zis = new ZipInputStream(bis);
				zis.getNextEntry();
				result = mapper.readValue(bis, theClass);
			}
		} catch (IOException e) {
			log("Exception : " + e.getMessage(), e);
		}
		return result;
	}

}
